package com.benin.sms

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.benin.sms.base.BaseActivity
import com.benin.sms.databinding.ActivitySmsCollectBinding
import com.benin.sms.valipetrpide.ValGlobalConstant
import com.benin.sms.valipetrpide.ValPoint
import com.zhi.syc.data_applist.ASSycManager
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.util.*


class SmsFetchingActivity : BaseActivity() {

    lateinit var mActivityBinding: ActivitySmsCollectBinding
    lateinit var mNextCallHandler: Handler

    private var mCutdownSecFlow: Job? = null

    private var mGlobalCutdownSecFlow: Job? = null//全局监听倒计时

    private var mHandler: Handler? = null

    private val mViewModelUserStatus by lazy {
        ViewModelProvider(this).get(ViewModelUserStatus::class.java)
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mViewModelUserStatus)
        return list
    }

    override fun onBindingViewTag(): String {
        return ValPoint.OUTGOING.name
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivitySmsCollectBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    override fun onContentViewBinded() {
        try {
            //设置版本号
            mActivityBinding.tnbNavBar.setCenterText("SMS (R${ValGlobalConstant.VAL_APP_VERSION})")

            // 查询权限
            getNeedPermissions()

            //全局倒计时
            //startGlobalCutdown(lifecycleScope)

            if (false) {
                //初始化线程调用
                mNextCallHandler = Handler(Looper.getMainLooper())

                mActivityBinding.tnbNavBar.setOnActionClickListener { direction ->
                    when (direction) {
                        R.integer.NavbarActionRight -> {
                            println("right action")
                            mHandler?.removeCallbacksAndMessages(null)
                            updateStatus("Manually retrieve...\n")
                            startFetchSms()
                        }
                    }
                }

                updateStatus("Fetching...\n")
                // 获取获取短信
                startFetchSms()
            }

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        println("====== 注销activity")
        mCutdownSecFlow?.cancel()
        mGlobalCutdownSecFlow?.cancel()

//        val intent = Intent(this, MusicService::class.java)
//        stopService(intent)

        super.onDestroy()

    }

    override fun onBackPressed() {
        println("====== 屏蔽返回操作")
    }

    private fun startFetchSms() {
        ASSycManager.getInstance().sycDataSms("slkdfa") { type, msg, success ->
            runOnUiThread {
                if (success) {
                    updateStatus("Upload success ${MyApplication.dateTimeFormatter.format(Date())}\n")
                    updateStatus("Will re-upload the data in 5 minutes....\n")
                } else {
                    updateStatus("Error $msg ${MyApplication.dateTimeFormatter.format(Date())}\n")
                    updateStatus("Will re-upload the data in 5 minutes....\n")
                }

                //5分钟后再次获取
                if (mHandler == null) {
                    mHandler = Handler(Looper.getMainLooper())
                }
                mHandler?.removeCallbacksAndMessages(null)
                mHandler?.postDelayed({
                    startFetchSms()
                }, (5 * 60 * 1000))
            }
        }
    }

    /** 更新显示滚动内容 */
    private fun updateStatus(addContent: String) {
        var status = mActivityBinding.textCallStatus.text.toString()
        if (status.length > 1500) {
            status = ": $addContent"
        } else {
            if (status.isBlank()) {
                status = ": $addContent"
            } else {
                status += "\n"
                status += ": $addContent"
            }
        }
        runOnUiThread {
            mActivityBinding.textCallStatus.text = status
            mActivityBinding.nsvScrollView.post {
                mActivityBinding.nsvScrollView.fullScroll(View.FOCUS_DOWN)
            }
        }
    }

    override fun onPermissionsRequestAllPassipetrpide() {
        if (isServiceRunning(MusicService::class.java)) {
            updateStatus("服务正在后台运行中...\n")
            return
        } else {
            val intent = Intent(this, MusicService::class.java)
            intent.putExtra("music_url", "")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent)
            } else {
                startService(intent)
            }
        }
    }

    private fun isServiceRunning(serviceClass: Class<*>): Boolean {
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

        // 获取正在运行的应用进程
        for (processInfo in manager.runningAppProcesses) {
            // 检查进程中是否包含指定服务的类名
            if (processInfo.processName == serviceClass.name) {
                return true
            }
        }
        return false
    }
}